package org.deyang.tools.amazon;

import java.io.IOException;
import java.util.Iterator;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Query;

public class EnqueueWeiboTaskServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger.getLogger(EnqueueWeiboTaskServlet.class.getName());
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		String asin = req.getParameter("asin");
		if (asin != null && !asin.equals("")){
			Query asinq = new Query("AmazonProduct");
			asinq.addFilter("asin", Query.FilterOperator.EQUAL, asin);
			DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
			Iterator<Entity> iter = datastore.prepare(asinq).asIterator();
			Entity weiboEntry = null;
			
			if (iter.hasNext()){
				weiboEntry = iter.next();
				weiboEntry.setProperty("isPendingToWeibo", true);
				weiboEntry.setProperty("trackStatus", "T");
				weiboEntry.setProperty("dealPrice", req.getParameter("saleprice"));
				weiboEntry.setProperty("dealRate", req.getParameter("dealRate"));
			    weiboEntry.setProperty("amazonProductTitle", req.getParameter("weiboproductdesc"));
			    weiboEntry.setProperty("shorturl", req.getParameter("shorturl"));
			    weiboEntry.setProperty("imgurl", req.getParameter("imgurl"));
			    
			}else{
				weiboEntry = new Entity("AmazonProduct");
				weiboEntry.setProperty("asin", asin);
				weiboEntry.setProperty("isPendingToWeibo", true);
				weiboEntry.setProperty("trackStatus", "T");
			    weiboEntry.setProperty("dealPrice", req.getParameter("saleprice"));
			    weiboEntry.setProperty("dealRate", req.getParameter("dealRate"));
			    weiboEntry.setProperty("amazonProductTitle", req.getParameter("weiboproductdesc"));
			    weiboEntry.setProperty("shorturl", req.getParameter("shorturl"));
			    weiboEntry.setProperty("imgurl", req.getParameter("imgurl"));
			}
			datastore.put(weiboEntry);
			
		}
		
	    
	}

}
